package com.wct.permission.config;

import com.wct.permission.security.ImageCodeAuthenticationFilter;
import com.wct.permission.security.MyAuthenticationFailureHandler;
import com.wct.permission.security.MyAuthenticationSuccessHandler;
import com.wct.permission.security.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;

import javax.sql.DataSource;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date 2020/2/12 0:18
 */
@Configuration
// 启动 SpringSecurity 过滤器链
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private DataSource dataSource;

    @Bean
    public MyUserDetailsService myUserDetailsService() {
        return new MyUserDetailsService();
    }

    @Bean
    public MyAuthenticationFailureHandler authenticationFailureHandler() {
        return new MyAuthenticationFailureHandler();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 相当于配置文件中的 <security:authentication-manager>
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder);
/*        auth.inMemoryAuthentication().
                withUser("eric").password(passwordEncoder.encode("123456"))
                .authorities("ROLE_PRODUCT_ADD", "ROLE_PRODUCT_LIST");
        auth.inMemoryAuthentication().
                withUser("jack").password(passwordEncoder.encode("123456"))
                .authorities("ROLE_PRODUCT_DELETE", "ROLE_PRODUCT_UPDATE");*/
    }

    /**
     * 相当于配置文件中的 <security:http>
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 添加自定义过滤器
        http.addFilterBefore(new ImageCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        // remember-me
        http.rememberMe()
                .rememberMeServices(rememberMeServices())
                .key("INTERNAL_SECRET_KEY")
                .tokenValiditySeconds(3600);

        http.authorizeRequests()
                .antMatchers("/css/*", "/js/*", "/img/*").permitAll()
                .antMatchers("/", "/imageCode", "/userLogin").permitAll()
                .antMatchers("/product/add").hasAnyAuthority("ROLE_PRODUCT_ADD")
                .antMatchers("/product/update").hasAnyAuthority("ROLE_PRODUCT_UPDATE")
                .antMatchers("/product/list").hasAnyAuthority("ROLE_PRODUCT_LIST")
                .antMatchers("/product/delete").hasAnyAuthority("ROLE_PRODUCT_DELETE")
                .antMatchers("/**").fullyAuthenticated()
                .and()
//                .httpBasic()
                .formLogin()
                .loginPage("/userLogin")
                .loginProcessingUrl("/login")
                .successHandler(new MyAuthenticationSuccessHandler())
                .failureHandler(new MyAuthenticationFailureHandler());
//                .successForwardUrl("/product/index")
//                .failureForwardUrl("/userLogin?error=true")
//                .and()
//                .csrf().disable();
    }

    /**
     * 返回 RememberMeServices 实例
     *
     * @return the remember me services
     */
    @Bean
    public RememberMeServices rememberMeServices() {
        JdbcTokenRepositoryImpl rememberMeTokenRepository = new JdbcTokenRepositoryImpl();
        // 此处需要设置数据源，否则无法从数据库查询验证信息
        rememberMeTokenRepository.setDataSource(dataSource);
        // 启动时建表
//        rememberMeTokenRepository.setCreateTableOnStartup(true);

        // 此处的 key 可以为任意非空值(null 或 "")，单必须和起前面
        // rememberMeServices(RememberMeServices rememberMeServices).key(key)的值相同
        PersistentTokenBasedRememberMeServices rememberMeServices =
                new PersistentTokenBasedRememberMeServices("INTERNAL_SECRET_KEY", myUserDetailsService, rememberMeTokenRepository);

        // 该参数不是必须的，默认值为 "remember-me", 但如果设置必须和页面复选框的 name 一致
        rememberMeServices.setParameter("remember-me");
        return rememberMeServices;
    }

}
